var core    = require("core")
,   crypto  = require("crypto")
,   db      = core.db
,   schema  = db.schema
,   utils   = core.utils
,   send    = core.send;

var GET = {
    path    : "/login",
    method  : "get",
    auth    : [
        function(opt, next){

            var err = null
            ,   url = null;
            if(0 === global.app.user.count){
                var token = utils.token.template(1, 1000 * 60 * 10);
                token.data = {
                    regAuth : 0,
                    status  : true
                };
                token = utils.token.createToken(token);
                url = '/register?token=' + token;
                err = new Error(new send(100018).msg);
            };
            next(err, url);
        },
        function(opt, next){

            var err = null;
            if(opt.sessions.user || opt.sessions.user)
                err = new Error(new send(100021).msg);
            next(err);

        }
    ],
    failUrl : [
        null,
        "/home"
    ]
};

var POST = {
    path    : "/login",
    method  : "post",
    auth    : function(opt, next){

        var body    = opt.body
        ,   options = {
            name : body.name,
            pwd  : crypto.createHash('sha1')
        };
        options.pwd.update(body.pwd+"");
        options.pwd = options.pwd.digest('hex');

        schema.User.findOne(options, function(err, User){

            if(err)
                return next(new Error(new send(500000).msg));

            if(!User){
                var token = utils.token.template(1, 3000);
                token.data = {
                    errcode : 100013
                };
                token = utils.token.createToken(token);
                return next(new Error(new send(100013).msg), "/login?token="+token);
            }

            if(!User.status)
                return next(new Error(new send(100012).msg));

            opt.body.user = {
                uid : User.uid,
                auth : User.auth,
                image : User.image,
                name  : User.name
            };

            next();

        });
    },
    failUrl : "/login"
};

exports.GET = GET;
exports.POST = POST;
